package cn.wen.forum.task;

import cn.wen.forum.common.util.RedisUtils;
import cn.wen.forum.constants.ForumConstant;
import cn.wen.forum.mapper.UserMapper;
import cn.wen.forum.pojo.entity.User;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @ClassName UpdateUserDataTask
 * @Author By wen
 * @Description 同步user信息数据
 * @Date 2023/8/15 9:51
 * @Version 1.0
 */
@Slf4j
@Component
public class UpdateUserDataTask {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserMapper userMappe;

    /**
     * 每半小时分钟执行一次数据同步
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void runimpl(){
        log.info("==>同步用户数据至数据库定时任务开始！");
        try {
            handler();
        } catch (Exception e) {
            log.error("==>定时任务执行异常：",e);
        }
        log.info("==>同步用户数据至数据库定时任务结束！");
    }

    public void handler() throws Exception{
        // 获取活跃用户set，同步用户经验值相关
        Set<String> cacheUserIDSet = redisUtils.getCacheSet(ForumConstant.USER_ACTIVE_INFO);
        log.info("==>当前需要同步共计数据条数:{};id集合:[{}],",cacheUserIDSet.size(),cacheUserIDSet);
        for(String userID:cacheUserIDSet) {
            // 根据id从缓存读取当前id所记录的用户信息
            Object obj = redisUtils.getCacheObject(ForumConstant.USER_INFO + userID);
            User userInfo = JSONObject.parseObject(obj.toString(), User.class);

            User user = new User();
            user.setId(Long.parseLong(userID));
            user.setEmpiricalValue(userInfo.getEmpiricalValue());
            user.setAttentionNum(userInfo.getAttentionNum());
            user.setPostNum(userInfo.getPostNum());
            user.setApprovalNum(userInfo.getApprovalNum());
            userMappe.updateById(user);
        }
        // 删除该缓存set
        redisUtils.deleteObject(ForumConstant.USER_ACTIVE_INFO);
    }
}
